package com.huacai.service.impl;

import com.huacai.domain.Comment;
import com.huacai.mapper.CommentMapper;
import com.huacai.service.ICommentService;
import com.huacai.common.utils.DateUtils;
import com.huacai.common.utils.uuid.IdUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.huacai.common.utils.SecurityUtils.getUserId;

/**
 * 评论Service业务层处理
 *
 * @author lundao
 * @date 2025-09-14
 */
@Service
public class CommentServiceImpl implements ICommentService
{
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 查询评论
     *
     * @param commentId 评论主键
     * @return 评论
     */
    @Override
    public Comment selectCommentByCommentId(String commentId)
    {
        return commentMapper.selectCommentByCommentId(commentId);
    }
    @Override
    public List<Comment> selectCommentByBlogId(String blogId)
    {
        return commentMapper.selectCommentByBlogId(blogId);
    }
    /**
     * 查询评论列表
     *
     * @param comment 评论
     * @return 评论
     */
    @Override
    public List<Comment> selectCommentList(Comment comment)
    {
        return commentMapper.selectCommentList(comment);
    }

    /**
     * 批量查询评论数
     * @param commentIds
     * @return
     */
    @Override
    public Map<String, Integer> batchSelectCommentCount(List<String> blogIds) {
        if (blogIds == null || blogIds.isEmpty()) {
            return Collections.emptyMap();
        }
        //每批处理500个ID
        int batchSize = 500;
        Map<String, Integer> finalResult = new HashMap<>();
        //分批处理
        for (int i = 0; i < blogIds.size(); i += batchSize) {
            int end = Math.min(i + batchSize, blogIds.size());
            List<String> batchIds = blogIds.subList(i, end);
            Map<String, Map<String, Object>> resultMap = commentMapper.batchSelectCommentCount(batchIds);
            resultMap.forEach((blogId, data) ->
                    finalResult.put(blogId, ((Number) data.get("commentCount")).intValue()));
        }
        return finalResult;
    }
    /**
     * 新增评论
     *
     * @param comment 评论
     * @return 结果
     */
    @Override
    public int insertComment(Comment comment)
    {
        comment.setCreateTime(DateUtils.getNowDate());
        comment.setCommentId(IdUtils.randomUUID());
        comment.setUserId(Math.toIntExact(getUserId()));
        return commentMapper.insertComment(comment);
    }

    /**
     * 批量新增评论
     *
     * @param comments 评论List
     * @return 结果
     */
    @Override
    public int batchInsertComment(List<Comment> comments)
    {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        int count = 0;
        if (!CollectionUtils.isEmpty(comments)) {
            try {
                for (int i = 0; i < comments.size(); i++) {
                    int row = commentMapper.insertComment(comments.get(i));
                    // 防止内存溢出，每100次提交一次,并清除缓存
                    boolean bool = (i >0 && i%100 == 0) || i == comments.size() - 1;
                    if (bool){
                        sqlSession.commit();
                        sqlSession.clearCache();
                    }
                    count = i + 1;
                }
            }catch (Exception e){
                e.printStackTrace();
                // 没有提交的数据可以回滚
                sqlSession.rollback();
            }finally {
                sqlSession.close();
                return count;
            }
        }
        return count;
    }

    /**
     * 修改评论
     *
     * @param comment 评论
     * @return 结果
     */
    @Override
    public int updateComment(Comment comment)
    {
        return commentMapper.updateComment(comment);
    }

    /**
     * 批量删除评论
     *
     * @param commentIds 需要删除的评论主键
     * @return 结果
     */
    @Override
    public int deleteCommentByCommentIds(String[] commentIds)
    {
        return commentMapper.deleteCommentByCommentIds(commentIds);
    }

    /**
     * 删除评论信息
     *
     * @param commentId 评论主键
     * @return 结果
     */
    @Override
    public int deleteCommentByCommentId(String commentId)
    {
        return commentMapper.deleteCommentByCommentId(commentId);
    }
}
